package com.ophiux.demo.subscribe;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * @desc: 订阅
 * @author: hhl
 * @date：2023/12/13 22:01
 */
@Slf4j
@UtilityClass
public class SubscribeSample2 {

    public static void main(String[] args) {
        SubscribeSample2.subscribe();
    }

    public void subscribe() {
        String broker = "tcp://iot-06z00btaemny5hn.mqtt.iothub.aliyuncs.com:1883";
        String topic = "hhltest";
        String username = "Device1&k0mahi4zn6H";
        String password = "2a3bed0e2ccec7e7a3704e265971be8e9f8c8ecaffe79be483f21a90870f10ac";
        String clientid = "mqttx_c0b6648223";
        int qos = 0;

        try {
            MqttClient client = new MqttClient(broker, clientid, new MemoryPersistence());
            // 连接参数
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setConnectionTimeout(600);
            options.setKeepAliveInterval(60);
            options.setAutomaticReconnect(true);
            // 设置回调
            client.setCallback(new MqttCallback() {

                /**
                 * 连接丢失时被调用
                 * @param cause
                 */
                public void connectionLost(Throwable cause) {
                    System.out.println("connectionLost: " + cause.getMessage());
                }

                /**
                 * 接收到消息时被调用
                 * @param topic
                 * @param message
                 */
                public void messageArrived(String topic, MqttMessage message) {
                    System.out.println("topic: " + topic);
                    System.out.println("Qos: " + message.getQos());
                    System.out.println("message content: " + new String(message.getPayload()));

                }

                /**
                 * 消息发送完成时被调用
                 * @param token
                 */
                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("deliveryComplete---------" + token.isComplete());
                }

            });
            client.connect(options);
            client.subscribe(topic, qos);
            System.out.println("Subscribed to topic: " + topic);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
